﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace FlashPay.Service.Impl
{
    using AutoMapper;
    using FlashPay.DAO.Bank;
    using FlashPay.DAO.Interface;
    using FlashPay.DAO.Order;
    using FlashPay.DAO.Sys;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.Bank;
    using FlashPay.Entity.Request.Payment;
    using FlashPay.Entity.Response.Bank;
    using FlashPay.Entity.Response.BankCard;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity.Response.Order;
    using FlashPay.Entity.Response.Sys;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Newtonsoft.Json;

    /// <summary>
    /// 银行业务接口实现
    /// </summary>
    public class BankServiceImpl : BankService
    {
        #region 注入
        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankInfoDAO _bankInfoDao;

        /// <summary>
        /// 订单数据接口
        /// </summary>
        private readonly OrderRecordDAO _orderRecordDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 银行卡类型记录
        /// </summary>
        private readonly BankCardTypeRecordDao _cardTypeRecordDao;

        /// <summary>
        /// 公司
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly SysConfigDao _sysConfigDao;

        /// <summary>
        /// 余额变化
        /// </summary>
        private readonly AdjustBalanceDao _adjustBalanceDao;
        

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }


        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="menu">菜单数据接口</param>
        /// <param name="menuPermission">菜单数据接口</param>
        public BankServiceImpl(BankDao bankDao, BankInfoDAO bankInfoDao, OrderRecordDAO orderRecordDao,
            LogDao logDao, LogRecord logRecord, BankCardTypeRecordDao cardTypeRecordDao, CompanyDao companyDao, SysConfigDao sysConfigDao, AdjustBalanceDao adjustBalanceDao,
            IMapper mapper, FlashPayContext context)
        {
            _bankDao = bankDao;
            _bankInfoDao = bankInfoDao;
            _orderRecordDao = orderRecordDao;
            _logDao = logDao;
            _logRecord = logRecord;
            _companyDao = companyDao;
            _sysConfigDao = sysConfigDao;
            _adjustBalanceDao = adjustBalanceDao;
            _mapper = mapper;
            _context = context;
            _cardTypeRecordDao = cardTypeRecordDao;
        }
        #endregion

        #region 获取所有銀行卡记录
        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public BankResponse Get(int bcId)
        {
            var bankResponse = new BankResponse();

            #region 银行
            var bankCard = _bankDao.GetById(bcId);
            if (bankCard != null)
            {
                bankResponse.Bcid = bankCard.Bcid;
                bankResponse.CardType = bankCard.CardType;
                bankResponse.CompanyId = bankCard.CompanyId;
                bankResponse.OrderNo = bankCard.OrderNo.ToString();
                bankResponse.BankCode = bankCard.BankCode;
                bankResponse.CardNumber = bankCard.CardNumber;
                bankResponse.SecCardNumber = bankCard.SecCardNumber;
                bankResponse.CardName = bankCard.CardName;
                bankResponse.UsingStatus = bankCard.UsingStatus;
                bankResponse.EnableStatus = bankCard.EnableStatus;
                bankResponse.LoginName = bankCard.LoginName;
                bankResponse.PasswordLogin = EncryptHelper.deCryptDES(bankCard.PasswordLogin);
                bankResponse.PasswordQuery = EncryptHelper.deCryptDES(bankCard.PasswordQuery);
                bankResponse.PasswordPay = EncryptHelper.deCryptDES(bankCard.PasswordPay);
                bankResponse.PasswordShield = EncryptHelper.deCryptDES(bankCard.PasswordShield);
                bankResponse.OriginalPassword = EncryptHelper.deCryptDES(bankCard.OriginalPassword);
                bankResponse.UsbType = bankCard.UsbType;
                bankResponse.UsbSerialNumber = bankCard.UsbSerialNumber;
                bankResponse.AccountBank = bankCard.AccountBank;
                bankResponse.DocumentNumber = bankCard.DocumentNumber;
                bankResponse.PhoneNumber = bankCard.PhoneNumber;
                bankResponse.PaymentStart = bankCard.PaymentStart;
                bankResponse.PaymentEnd = bankCard.PaymentEnd;
                bankResponse.PayFeeRatio = bankCard.PayFeeRatio > 0 ? bankCard.PayFeeRatio * 100 : 0;
                bankResponse.CrossBankPay = bankCard.CrossBankPay;
                bankResponse.DepositType = bankCard.DepositType;
                bankResponse.DepositFeeRatio = bankCard.DepositFeeRatio > 0 ? bankCard.DepositFeeRatio * 100 : 0;
                bankResponse.Remark = bankCard.Remark;
                bankResponse.UsingStatusRemark = bankCard.UsingStatusRemark;
                bankResponse.IpAddress = bankCard.IpAddress;
                bankResponse.VmClientId = bankCard.VmClientId;
                bankResponse.PaymentType = bankCard.PaymentType;
                bankResponse.AliPayCardIndex = bankCard.AliPayCardIndex;
                bankResponse.AliPayBankMark = bankCard.AliPayBankMark;
                bankResponse.AliPayCardName = bankCard.AliPayCardName;
            }
            #endregion

            return bankResponse;
        }

        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public BankResponse Get(int companyId, int bcId, List<string> userPermission)
        {
            var bankResponse = new BankResponse();

            #region 银行
            var bankCard = _bankDao.GetById(bcId);
            if (bankCard != null)
            {
                bankResponse.Bcid = bankCard.Bcid;
                bankResponse.CardType = bankCard.CardType;
                bankResponse.CompanyId = bankCard.CompanyId;
                bankResponse.OrderNo = bankCard.OrderNo.ToString();
                bankResponse.BankCode = bankCard.BankCode;
                bankResponse.CardNumber = bankCard.CardNumber;
                bankResponse.SecCardNumber = bankCard.SecCardNumber;
                bankResponse.CardName = bankCard.CardName;
                bankResponse.UsingStatus = bankCard.UsingStatus;
                bankResponse.EnableStatus = bankCard.EnableStatus;
                bankResponse.LoginName = bankCard.LoginName;
                bankResponse.PasswordLogin = EncryptHelper.deCryptDES(bankCard.PasswordLogin);
                bankResponse.PasswordQuery = EncryptHelper.deCryptDES(bankCard.PasswordQuery);
                bankResponse.PasswordPay = EncryptHelper.deCryptDES(bankCard.PasswordPay);
                bankResponse.PasswordShield = EncryptHelper.deCryptDES(bankCard.PasswordShield);
                bankResponse.OriginalPassword = EncryptHelper.deCryptDES(bankCard.OriginalPassword);
                bankResponse.UsbType = bankCard.UsbType;
                bankResponse.UsbSerialNumber = bankCard.UsbSerialNumber;
                bankResponse.AccountBank = bankCard.AccountBank;
                bankResponse.DocumentNumber = bankCard.DocumentNumber;
                bankResponse.PhoneNumber = bankCard.PhoneNumber;
                bankResponse.PaymentStart = bankCard.PaymentStart;
                bankResponse.PaymentEnd = bankCard.PaymentEnd;
                bankResponse.PayFeeRatio = bankCard.PayFeeRatio > 0 ? bankCard.PayFeeRatio * 100 : 0;
                bankResponse.CrossBankPay = bankCard.CrossBankPay;
                bankResponse.DepositType = bankCard.DepositType;
                bankResponse.DepositFeeRatio = bankCard.DepositFeeRatio > 0 ? bankCard.DepositFeeRatio * 100 : 0;
                bankResponse.Remark = bankCard.Remark;
                bankResponse.AliPayCardIndex = bankCard.AliPayCardIndex;
                bankResponse.AliPayBankMark = bankCard.AliPayBankMark;
                bankResponse.AliPayCardName = bankCard.AliPayCardName;
                bankResponse.UsingStatusRemark = bankCard.UsingStatusRemark;
                if (userPermission.Contains("PaymentRecord0013"))
                {
                    bankResponse.RemarkPermission = "PaymentRecord0013";
                }
                bankResponse.IpAddress = bankCard.IpAddress;
                bankResponse.VmClientId = bankCard.VmClientId;
                bankResponse.PaymentType = bankCard.PaymentType;
                if (bankCard.CompanyId > 0) {
                    var company = _companyDao.GetById(bankCard.CompanyId);
                    if (company != null) {
                        bankResponse.CompanyName = company.CompanyName;
                    }
                }
                //中转费率
                bankResponse.TransportRate = bankCard.TransportRate > 0 ? bankCard.TransportRate * 100 : 0;

                #region 中转卡
                var transportCard = _bankDao.GetTransportCard(bankCard.Bcid);
                if (transportCard != null)
                {
                    var transportCardResponse = new TransportCardResponse();

                    bankResponse.TransportCardResponse = new TransportCardResponse()
                    {
                        OrderSource = transportCard.OrderSource,
                        TransportMethod = transportCard.TransportMethod,
                        ShowedOnDepositCard = transportCard.ShowedOnDepositCard,
                        TriggeredAmount = transportCard.TriggeredAmount,
                        TransferredAmount = transportCard.TransferredAmount,
                        PreservedBalance = transportCard.PreservedBalance,
                        DestinationCardType = transportCard.DestinationCardType,
                        DestinationOrderSideBalance = transportCard.DestinationOrderSideBalance,
                        DestinationBankCode = transportCard.DestinationBankCode,
                        DestinationBCID = transportCard.DestinationBCID
                    };
                    //中转转入卡
                    var selectTransferCardResponses = from tc in _context.TransportCardRule
                             join
                             bc in _context.BankCard on tc.DestinationBcid equals bc.Bcid
                             where tc.TransportCardBcid == transportCard.Bcid orderby tc.Priority ascending
                              select new SelectTransferCardResponse
                             {
                                 Id = bc.Bcid,
                                 Description = bc.BankCode +""+bc.CardName,
                                 AmountLimit = tc.DestinationBcidamountLimit.ToString("#0")
                             };

                    if (selectTransferCardResponses != null && selectTransferCardResponses.Any())
                    {
                        bankResponse.SelectTransferCardResponse = selectTransferCardResponses.ToList();
                    }
                }
                #endregion

                #region 图片处理
                if (!string.IsNullOrEmpty(bankCard.BankPhoto))
                {
                    try
                    {
                        bankResponse.DocumentResponse = JsonConvert.DeserializeObject<List<DocumentResponse>>(bankCard.BankPhoto);
                    }
                    catch
                    {
                    }
                }
                #endregion

                #region 银行卡关联订单信息
                var order = _orderRecordDao.Get(bankCard.OrderNo);
                if (order != null)
                {
                    bankResponse.DepositUID = order.DepositUid;
                    bankResponse.ReceiptUID = order.ReceiptUid;
                }
                #endregion

                #region 银行卡额外信息
                var bankCardExtraLimit = _bankDao.GetByCardNumber(bankCard.CardNumber);
                if (bankCardExtraLimit != null)
                {
                    bankResponse.BankCardExtraLimitResponse = _mapper.Map<BankCardExtraLimitResponse>(bankCardExtraLimit);
                }
                #endregion

                #region 付款类型配置

                var sysConfigLists = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
                if (sysConfigLists != null && sysConfigLists.Any())
                {
                    var sysConfig = sysConfigLists.FirstOrDefault(p => p.ConfigValue == bankCard.PaymentType);
                    if (sysConfig != null) {
                        bankResponse.PaymentTypeName = sysConfig.ConfigContent;
                    }
                }
                #endregion

            }
            #endregion

            #region 公司列表
            var companys = this.GetCompany(companyId);

            var companyResponse = new List<CompanyResponse>();
            foreach (var item in companys)
            {
                companyResponse.Add(new CompanyResponse()
                {
                    CompanyID = item.CompanyID,
                    CompanyName = item.CompanyName,
                });
            }
            bankResponse.CompanyResponse = companyResponse;
            #endregion

            #region 银行
            var bankinfoList = _bankInfoDao.GetBankInfoList();

            var bankinfoResponse = new List<BankInfoResponse>();

            if (bankinfoList != null)
            {
                foreach (var item in bankinfoList)
                {
                    bankinfoResponse.Add(new BankInfoResponse()
                    {
                        BankCode = item.BankCode,
                        BankName = item.BankName
                    });
                }
            }
            bankResponse.BankInfoResponse = bankinfoResponse;
            #endregion

            #region 银行卡
            var companyIds = _bankDao.GetCompany(companyId).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any()) {

                var bankCardResponses = _bankDao.GetCompanyBankCard(companyIds);
                if (bankCardResponses != null && bankCardResponses.Any()) {

                    var companyBankCardResponse = new List<CompanyBankCardResponse>();

                    foreach (var item in bankCardResponses)
                    {
                        var cardTypeName = "";
                        switch (item.CardType) {
                            case 1:
                                cardTypeName = "收款卡";
                                break;
                            case 2:
                                cardTypeName = "中款卡";
                                break;
                            case 3:
                                cardTypeName = "付款卡";
                                break;
                            default:
                                cardTypeName = "";
                                break;
                        }
                        companyBankCardResponse.Add(new CompanyBankCardResponse()
                        {
                            BcId = item.BcId,
                            CardName = item.CardName,
                            CardTypeName = cardTypeName,
                            BankCode = item.BankCode,
                            CardNumber = item.CardNumber,
                        });
                    }

                    bankResponse.CompanyBankCardResponse = companyBankCardResponse;
                }
                
            }
            
            #endregion

            #region 订单列表
            var orders = _orderRecordDao.GetAuditingOrderRecord(companys.Select(p => p.CompanyID).ToList());
            if (orders != null && orders.Any())
            {
                var orderRecordResponse = new List<OrderRecordResponse>();
                orders.ForEach(item =>
                {
                    orderRecordResponse.Add(new OrderRecordResponse()
                    {
                        OrderNo = item.OrderNo.ToString()
                    });
                });
                bankResponse.OrderRecordResponse = orderRecordResponse;
            }
            #endregion

            #region 付款类型配置

            var sysConfigList = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
            if (sysConfigList != null && sysConfigList.Any()) {
                var sysConfigResponse = new List<SysConfigResponse>();
                sysConfigList.ForEach(item => {
                    sysConfigResponse.Add(new SysConfigResponse() {
                        ConfigValue = item.ConfigValue,
                        ConfigContent = item.ConfigContent
                    });
                });
                bankResponse.SysConfigResponse = sysConfigResponse;
            }
            #endregion

            return bankResponse;
        }
        #endregion

        #region 银行卡[更改启用状态]
        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult UpdateEnableStatus(int bcId, sbyte enableStatus,string userName)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bank = _bankDao.GetById(bcId);
                if (bank == null)
                {
                    throw new Exception("银行卡记录不存在！");
                }

                if (bank.EnableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                {
                    throw new Exception("银行卡未授权不能操作！");
                }

                if (_bankDao.UpdateEnableStatus(bcId, enableStatus))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.CreateName = userName;
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态成功,卡号：{0},用户名：{1},状态值：{2}", bank.CardNumber, bank.CardName, enableStatus);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态失败,银行卡编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 更改库存卡启用状态
        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult StockCardDelete(int bcId)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bankCard = _bankDao.GetById(bcId);
                if (bankCard == null)
                {
                    throw new Exception("银行卡记录不存在！");
                }

                if (bankCard.EnableStatus != 4)
                {
                    throw new Exception("库存卡必须为未授权状态!！");
                }

                if (bankCard.CompanyId > 0)
                {
                    throw new Exception("库存卡必须未分配公司!");
                }

                var order = _orderRecordDao.Get(bankCard.OrderNo);
                if (order.ReceiptUid > 0 || order.PayUid > 0)
                {
                    throw new Exception("订单已确认收货!");
                }

                if (_bankDao.DeleteByBcId(bcId))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCardPare_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("删除银行卡成功,编号：{0}", bcId);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCardPare_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("删除银行卡失败,编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 获取所有銀行卡记录
        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<BankCard> GetList(BankQuery query)
        {
            return _bankDao.GetList(query);
        }
        #endregion

        #region 银行卡[添加、修改]
        /// <summary>
        /// 银行卡修改
        /// </summary>
        /// <param name="request">参数</param>
        public JResult EditOrAdd(BankEditOrAddRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {

                    #region 数据验证

                    var cardTypes = new List<int>()
                    {
                        CardType.收款卡.GetHashCode(),
                        CardType.中转卡.GetHashCode(),
                        CardType.付款卡.GetHashCode()
                    };

                    //公司名称
                    if (cardTypes.Contains(request.CardType))
                    {
                        if (request.CompanyId <= 0)
                        {
                            throw new Exception("收款卡必须选择公司！");
                        }
                    }
                    //银行副卡号
                    //if (!string.IsNullOrEmpty(request.SecCardNumber))
                    //{
                    //    var secCardNumberReg = new Regex(@"^.{12,20}$");
                    //    if (!secCardNumberReg.IsMatch(request.SecCardNumber))
                    //    {
                    //        throw new Exception("银行副卡号必须介于 12 和 20 之间");
                    //    }
                    //}
                    //银行卡使用状态
                    if (!request.UsingStatus.HasValue)
                    {
                        throw new Exception("请选择银行卡使用状态！");
                    }
                    //银行卡启用状态
                    if (!request.EnableStatus.HasValue)
                    {
                        throw new Exception("请选择银行卡启用状态！");
                    }
                    //查询密码
                    if (!string.IsNullOrEmpty(request.PasswordQuery))
                    {
                        if (request.PasswordQuery.Length < 6 || request.PasswordQuery.Length > 40)
                        {
                            throw new Exception("查询密码必须介于 6 和 40 之间");
                        }
                    }
                    //原始密码
                    //if (string.IsNullOrEmpty(request.OriginalPassword))
                    //{
                    //    throw new Exception("原始密码必须介于 6 和 40 之间");
                    //}
                    //var originalPasswordReg = new Regex(@"^.{6,40}$");
                    //if (!originalPasswordReg.IsMatch(request.OriginalPassword.ToString()))
                    //{
                    //    throw new Exception("原始密码必须介于 6 和 40 之间");
                    //}
                    //网盾类型
                    if (!request.UsbType.HasValue)
                    {
                        throw new Exception("请选择网盾类型！");
                    }

                    #region 中转卡
                    if (request.CardType == CardType.中转卡.GetHashCode())
                    {
                        //中转卡费率
                        if (string.IsNullOrEmpty(request.TransportRate))
                        {
                            throw new Exception("中转费率最大保留四位小数，整数最多保留五位");
                        }
                        var transportRateReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!transportRateReg.IsMatch(request.TransportRate))
                        {
                            throw new Exception("中转费率最大保留四位小数，整数最多保留五位");
                        }
                        //是否显示存款卡中
                        if (request.ShowedOnDepositCard <= 0)
                        {
                            throw new Exception("请选择是否显示存款卡中.");
                        }
                        if (!new List<int> { 1, 2 }.Contains(request.ShowedOnDepositCard))
                        {
                            throw new Exception("请选择是否显示存款卡中");
                        }
                        //触发中转金额
                        if (string.IsNullOrEmpty(request.TriggeredAmount))
                        {
                            throw new Exception("触发中转金额最大保留四位小数，整数最多保留五位");
                        }
                        var triggeredAmountReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!triggeredAmountReg.IsMatch(request.TriggeredAmount))
                        {
                            throw new Exception("触发中转金额最大保留四位小数，整数最多保留五位");
                        }
                        //每次中转金额
                        if (string.IsNullOrEmpty(request.TransferredAmount))
                        {
                            throw new Exception("每次中转金额最大保留四位小数，整数最多保留五位");
                        }
                        var transferredAmountReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!transferredAmountReg.IsMatch(request.TransferredAmount))
                        {
                            throw new Exception("每次中转金额最大保留四位小数，整数最多保留五位");
                        }
                        //预留账户金额
                        if (string.IsNullOrEmpty(request.PreservedBalance))
                        {
                            throw new Exception("预留账户金额最大保留四位小数，整数最多保留五位");
                        }
                        var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!preservedBalanceReg.IsMatch(request.PreservedBalance))
                        {
                            throw new Exception("预留账户金额最大保留四位小数，整数最多保留五位");
                        }

                        //触发中转金额必须大于预留账户金额
                        if (decimal.Parse(request.TriggeredAmount) < decimal.Parse(request.PreservedBalance))
                        {
                            throw new Exception("触发中转金额必须大于预留账户金额");
                        }
                        //中转方式
                        if (request.TransportMethod <= 0)
                        {
                            throw new Exception("请选择中转方式.");
                        }

                        if (!new List<int> { 1, 2 }.Contains(request.TransportMethod))
                        {
                            throw new Exception("请选择中转方式");
                        }
                        //转入卡余额
                        if (string.IsNullOrEmpty(request.DestinationOrderSideBalance))
                        {
                            throw new Exception("转入卡余额不能为空.");
                        }
                        var destinationOrderSideBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!destinationOrderSideBalanceReg.IsMatch(request.DestinationOrderSideBalance))
                        {
                            throw new Exception("转入卡余额最大保留四位小数，整数最多保留五位");
                        }
                    }
                    #endregion

                    #region 付款卡
                    if (request.CardType == CardType.付款卡.GetHashCode())
                    {
                        //付款区间起
                        var paymentStartReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PaymentStart.ToString()))
                        {
                            throw new Exception("付款区间起最大保留四位小数，整数最多保留五位");
                        }
                        //付款区间迄
                        var paymentEndReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PaymentEnd.ToString()))
                        {
                            throw new Exception("付款区间迄最大保留四位小数，整数最多保留五位");
                        }
                        //付款区间迄大于付款区间起
                        var paymentStart = decimal.Parse(request.PaymentStart);
                        var paymentEnd = decimal.Parse(request.PaymentEnd);
                        if (paymentEnd <= paymentStart)
                        {
                            throw new Exception("付款区间迄必须大于付款区间起");
                        }
                        //付款费率
                        var payFeeRatioReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PayFeeRatio.ToString()))
                        {
                            throw new Exception("付款费率最大保留四位小数，整数最多保留五位");
                        }

                        var sysConfigList = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
                        if (sysConfigList == null || sysConfigList.Count <= 0) {
                            throw new Exception("请设置公司的付款类型");
                        }

                        if (!request.PaymentType.HasValue) {
                            throw new Exception("请设置公司的付款类型");
                        }

                        var configValueArray = sysConfigList.Select(p => p.ConfigValue).ToList();
                        if (!configValueArray.Contains(request.PaymentType.Value)) {
                            throw new Exception("请设置公司的付款类型");
                        }
                    }
                    #endregion

                    //跨行转账
                    if (!request.CrossBankPay.HasValue)
                    {
                        throw new Exception("请选择跨行转账！");
                    }
                    //证件号码
                    if (!string.IsNullOrEmpty(request.DocumentNumber))
                    {
                        var documentNumberReg = new Regex(@"^.{0,40}$");
                        if (!documentNumberReg.IsMatch(request.DocumentNumber))
                        {
                            throw new Exception("证件号码必须介于 0 和 40 之间");
                        }
                    }
                    //存款等级
                    if (request.CardType == CardType.付款卡.GetHashCode())
                    {
                        if (string.IsNullOrEmpty(request.DepositType))
                        {
                            throw new Exception("请选择存款等级");
                        }
                    }
                    else
                    {

                        var depositFeeRatioReg = new Regex(@"^(([1-9]\d{0,3})|0)(?:\.[0-9]{1,4})?$");
                        if (!depositFeeRatioReg.IsMatch(request.DepositFeeRatio.ToString()))
                        {
                            throw new Exception("收款费率最大保留四位小数，整数最多保留四位");
                        }
                    }
                    //额外限制
                    var bankCardExtraLimit = new BankCardExtraLimit();
                    if(request.CardType == CardType.收款卡.GetHashCode() || request.CardType == CardType.中转卡.GetHashCode() || request.CardType == CardType.付款卡.GetHashCode())
                    {
                        //限制收款金额
                        if (!string.IsNullOrEmpty(request.LimitDepositAmount))
                        {
                            var limitDepositAmountReg = new Regex(@"^(([1-9]\d{0,7})|0)(?:\.[0-9]{1,2})?$");
                            if (!limitDepositAmountReg.IsMatch(request.LimitDepositAmount))
                            {
                                throw new Exception("限制收款金额最大保留二位小数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitDepositAmount = decimal.Parse(request.LimitDepositAmount);
                        }
                        //限制收款笔数
                        if (!string.IsNullOrEmpty(request.LimitDepositCount))
                        {
                            var limitDepositCountReg = new Regex(@"^(([1-9]\d{0,7})|0)?$");
                            if (!limitDepositCountReg.IsMatch(request.LimitDepositCount))
                            {
                                throw new Exception("限制收款笔数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitDepositCount = int.Parse(request.LimitDepositCount);
                        }
                        //限制付款金额
                        if (!string.IsNullOrEmpty(request.LimitPayAmount))
                        {
                            var limitPayAmountReg = new Regex(@"^(([1-9]\d{0,7})|0)(?:\.[0-9]{1,2})?$");
                            if (!limitPayAmountReg.IsMatch(request.LimitPayAmount))
                            {
                                throw new Exception("限制付款金额最大保留二位小数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitPayAmount = decimal.Parse(request.LimitPayAmount);
                        }
                        //限制付款笔数
                        if (!string.IsNullOrEmpty(request.LimitPayCount))
                        {
                            var limitPayCountReg = new Regex(@"^(([1-9]\d{0,7})|0)?$");
                            if (!limitPayCountReg.IsMatch(request.LimitPayCount))
                            {
                                throw new Exception("限制付款笔数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitPayCount = int.Parse(request.LimitPayCount);
                        }
                        //状态
                        if (request.LimitStatus.HasValue)
                        {
                            var limit = new List<int>() { 1, 2 };

                            if (!limit.Contains(request.LimitStatus.Value))
                            {
                                throw new Exception("状态参数错误");
                            }
                            bankCardExtraLimit.LimitStatus = request.LimitStatus.Value;
                        }
                        else
                        {
                            throw new Exception("请选择额外限制状态.");
                        }
                    }
                    #endregion

                    if (request.BcId > 0)
                    {
                        var model = _bankDao.GetById(request.BcId, _context);

                        var requestData = JsonConvert.SerializeObject(model);
                        if (model == null)
                        {
                            throw new Exception("获取银行卡记录失败！");
                        }

                        //状态验证
                        if (model.EnableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                        {
                            throw new Exception("银行卡未授权不能操作！");
                        }

                        #region 银行卡类型记录
                        if (model.CardType != request.CardType)
                        {
                            var recordType = model.CardType == (sbyte)CardType.备用卡.GetHashCode() ? (sbyte)1 : (sbyte)2;
                            var bankCardTypeRecord = new BankCardTypeRecord()
                            {
                                CardNumber = model.CardNumber,
                                BeforeCardType = model.CardType,
                                AfterCardType = request.CardType,
                                RecordType = recordType,
                                CreateUid = request.UserId,
                                CreateDbdate = DateTime.Now
                            };
                            var bankCardTypeRecordId = _bankDao.BankCardTypeRecordAdd(bankCardTypeRecord, _context);
                            if (bankCardTypeRecordId <= 0)
                            {
                                throw new Exception("创建银行卡类型记录失败！");
                            }
                        }
                        #endregion

                        #region 银行卡
                        //公司名称
                        if (cardTypes.Contains(request.CardType))
                        {
                            model.CompanyId = request.CompanyId;
                        }
                        else
                        {
                            model.CompanyId = 0;
                        }

                        model.CardType = request.CardType;
                        model.UsingStatus = request.UsingStatus.Value;
                        model.EnableStatus = request.EnableStatus.Value;
                        model.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                        model.UsbType = request.UsbType.Value;
                        if (request.CardType == CardType.付款卡.GetHashCode())
                        {
                            model.PaymentStart = decimal.Parse(request.PaymentStart);
                            model.PaymentEnd = decimal.Parse(request.PaymentEnd);
                            model.PayFeeRatio = decimal.Parse(request.PayFeeRatio) > 0 ? decimal.Parse(request.PayFeeRatio) / 100 : 0; ;
                            model.CrossBankPay = request.CrossBankPay.Value;
                            model.DepositType = request.DepositType;
                            model.PaymentType = request.PaymentType.Value;
                        }
                        else if (request.CardType == (sbyte)CardType.中转卡.GetHashCode())
                        {
                            model.TransportRate = decimal.Parse(request.TransportRate) / 100;
                        }
                        else
                        {
                            model.PaymentStart = 0;
                            model.PaymentEnd = 0;
                            model.PayFeeRatio = 0;
                            model.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                            model.DepositType = "";
                            model.DepositFeeRatio = decimal.Parse(request.DepositFeeRatio) > 0 ? decimal.Parse(request.DepositFeeRatio) / 100 : 0;
                        }
                        model.AliPayCardIndex = request.AliPayCardIndex;
                        model.AliPayBankMark = request.AliPayBankMark;
                        model.AliPayCardName = request.AliPayCardName;
                        model.Remark = request.Remark;

                        if (!_bankDao.Update(model, _context))
                        {
                            throw new Exception("修改银行卡信息失败！");
                        }

                        var bankCardExtraLimitModel = _bankDao.GetByCardNumber(model.CardNumber, _context);
                        if (bankCardExtraLimitModel != null)
                        {

                            if (!string.IsNullOrEmpty(request.LimitDepositAmount))
                            {
                                bankCardExtraLimitModel.LimitDepositAmount = decimal.Parse(request.LimitDepositAmount);
                            }
                            if (!string.IsNullOrEmpty(request.LimitDepositCount))
                            {
                                bankCardExtraLimitModel.LimitDepositCount = Int32.Parse(request.LimitDepositCount);
                            }
                            if (!string.IsNullOrEmpty(request.LimitPayAmount))
                            {
                                bankCardExtraLimitModel.LimitPayAmount = decimal.Parse(request.LimitPayAmount);
                            }
                            if (!string.IsNullOrEmpty(request.LimitPayCount))
                            {
                                bankCardExtraLimitModel.LimitPayCount = Int32.Parse(request.LimitPayCount);
                            }
                            if (request.LimitStatus.HasValue)
                            {
                                bankCardExtraLimitModel.LimitStatus = request.LimitStatus.Value;
                            }
                            if (!_bankDao.BankCardExtraLimitUpdate(bankCardExtraLimitModel, _context))
                            {
                                throw new Exception("修改银行卡额外限制失败！");
                            }
                        }
                        else
                        {
                            bankCardExtraLimit.CardNumber = model.CardNumber;
                            if (string.IsNullOrEmpty(_bankDao.BankCardExtraLimitAdd(bankCardExtraLimit, _context)))
                            {
                                throw new Exception("添加银行卡额外限制失败！");
                            }
                        }
                        #endregion

                        #region 中转卡
                        var transportCard = _bankDao.GetTransportCard(model.Bcid, _context);
                        if (transportCard != null)
                        {
                            transportCard.ShowedOnDepositCard = request.ShowedOnDepositCard;
                            transportCard.TriggeredAmount = decimal.Parse(request.TriggeredAmount);
                            transportCard.TransferredAmount = decimal.Parse(request.TransferredAmount);
                            transportCard.PreservedBalance = decimal.Parse(request.PreservedBalance);
                            transportCard.TransportMethod = (sbyte)request.TransportMethod;
                            if (request.TransportMethod == (int)TransportTransferMethod.自动)
                            {
                                if (request.DestinationCardType != null && request.DestinationCardType.Any())
                                {
                                    transportCard.DestinationCardType = String.Join(",", request.DestinationCardType);
                                }
                                else
                                {
                                    transportCard.DestinationCardType = null;
                                }

                                transportCard.DestinationOrderSideBalance = decimal.Parse(request.DestinationOrderSideBalance);
                                if (request.DestinationBankCodes != null && request.DestinationBankCodes.Any())
                                {
                                    transportCard.DestinationBankCode = String.Join(",", request.DestinationBankCodes);
                                }
                                else
                                {
                                    transportCard.DestinationBankCode = null;
                                }
                                transportCard.DestinationBCID = null;

                                //删除授权信息
                                //var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                                //_context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                                //_context.SaveChanges();
                            }
                            else
                            {
                                transportCard.DestinationCardType = null;
                                transportCard.DestinationBankCode = null;
                                if (request.TransportCardRules == null)
                                {
                                    throw new Exception("请选择转入卡！");
                                }

                                var _transportCardRule = new List<TransportCardRule>();

                                if (request.TransportCardRules.Any())
                                {
                                    sbyte row = 1;

                                    request.TransportCardRules.ForEach(item => {

                                        if (string.IsNullOrEmpty(item.DestinationBcidamountLimit))
                                        {
                                            throw new Exception("转入卡限定金额不能为空.");
                                        }

                                        var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,5})|0)?$");
                                        if (!preservedBalanceReg.IsMatch(item.DestinationBcidamountLimit))
                                        {
                                            throw new Exception("转入卡限定金额最多保留五位整数");
                                        }

                                        _transportCardRule.Add(new TransportCardRule()
                                        {
                                            TransportCardBcid = transportCard.Bcid,
                                            Priority = row,
                                            DestinationBcid = item.DestinationBcid,
                                            DestinationBcidamountLimit = Convert.ToInt32(item.DestinationBcidamountLimit)
                                        });

                                        row++;
                                    });
                                }

                                if (_transportCardRule != null && _transportCardRule.Any())
                                {
                                    //删除授权信息
                                    var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                                    _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                                    _context.SaveChanges();
                                    //批量新增
                                    _context.TransportCardRule.AddRange(_transportCardRule);
                                    _context.SaveChanges();
                                }
                            }
                            var transportCardUpdateStatus = _bankDao.TransportCardUpdate(transportCard);
                            if (!transportCardUpdateStatus)
                            {
                                throw new Exception("修改中转卡失败！");
                            }
                        }
                        else
                        {
                            transportCard = new TransportCard();
                            transportCard.Bcid = request.BcId;
                            transportCard.ShowedOnDepositCard = request.ShowedOnDepositCard;
                            transportCard.TriggeredAmount = decimal.Parse(request.TriggeredAmount);
                            transportCard.TransferredAmount = decimal.Parse(request.TransferredAmount);
                            transportCard.PreservedBalance = decimal.Parse(request.PreservedBalance);
                            if (request.TransportMethod == (int)TransportTransferMethod.自动)
                            {
                                if (request.DestinationCardType != null && request.DestinationCardType.Any())
                                {
                                    transportCard.DestinationCardType = String.Join(",", request.DestinationCardType);
                                }
                                else
                                {
                                    transportCard.DestinationCardType = null;
                                }

                                transportCard.DestinationOrderSideBalance = decimal.Parse(request.DestinationOrderSideBalance);
                                if (request.DestinationBankCodes != null && request.DestinationBankCodes.Any())
                                {
                                    transportCard.DestinationBankCode = String.Join(",", request.DestinationBankCodes);
                                }
                                else
                                {
                                    transportCard.DestinationBankCode = null;
                                }
                                transportCard.DestinationBCID = null;
                                //删除授权信息
                                var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                                _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                                _context.SaveChanges();
                            }
                            else
                            {
                                transportCard.DestinationCardType = null;
                            }

                            var transportCardUpdateStatus = _bankDao.TransportCardAdd(transportCard);
                            if (transportCardUpdateStatus <= 0)
                            {
                                throw new Exception("新增中转卡失败！");
                            }

                            if (request.TransportMethod == (int)TransportTransferMethod.手动)
                            {
                                if (request.TransportCardRules == null)
                                {
                                    throw new Exception("请选择转入卡！");
                                }

                                var _transportCardRule = new List<TransportCardRule>();

                                if (request.TransportCardRules.Any())
                                {
                                    sbyte row = 1;

                                    request.TransportCardRules.ForEach(item => {

                                        if (string.IsNullOrEmpty(item.DestinationBcidamountLimit))
                                        {
                                            throw new Exception("转入卡限定金额不能为空.");
                                        }

                                        var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)?$");
                                        if (!preservedBalanceReg.IsMatch(item.DestinationBcidamountLimit))
                                        {
                                            throw new Exception("转入卡限定金额最多保留五位整数");
                                        }

                                        _transportCardRule.Add(new TransportCardRule()
                                        {
                                            TransportCardBcid = transportCard.Bcid,
                                            Priority = row,
                                            DestinationBcid = item.DestinationBcid,
                                            DestinationBcidamountLimit = Convert.ToInt32(item.DestinationBcidamountLimit)
                                        });

                                        row++;
                                    });
                                }

                                if (_transportCardRule != null && _transportCardRule.Any())
                                {
                                    //删除授权信息
                                    var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                                    _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                                    _context.SaveChanges();
                                    //批量新增
                                    _context.TransportCardRule.AddRange(_transportCardRule);
                                    _context.SaveChanges();
                                }
                            }
                        }
                        #endregion

                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑银行卡成功,权限编号：{0}", model.Bcid);
                        _logRecord.RequestData = requestData;
                        _logRecord.AffectData = JsonConvert.SerializeObject(model);
                        _logDao.Insert(_logRecord);

                        tran.Commit();

                        response.Success = true;
                        response.SuccessMessage = "修改成功！";
                    }
                    else
                    {
                        throw new Exception("参数错误！");
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        tran.Rollback();
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑银行卡失败,权限编号：{0}", request.BcId);
                        _logDao.Insert(_logRecord);
                        //日志
                        response.ErrorMessage = ex.Message;
                    }
                    catch
                    {
                    }

                }
            }
            return response;
        }
        #endregion

        #region 库存卡[添加、修改]
        /// <summary>
        /// 添加、修改银行卡
        /// </summary>
        /// <param name="request"></param>
        public JResult StockCardAddOrEdit(StockCardAddOrEditRequest request)
        {

            var result = new JResult()
            {
                Success = false
            };

            try
            {
                #region 数据验证
                //银行
                var bankInfo = _bankInfoDao.GetByBankCode(request.BankCode);
                if (bankInfo == null)
                {
                    throw new Exception("银行信息不存在！");
                }


                //var bankCardNumbers = _bankDao.GetList(new BankQuery() { NoEqualBcId = request.BCId, CardNumber = request.CardNumber });
                //if (bankCardNumbers != null && bankCardNumbers.Any())
                //{
                //    throw new Exception("银行卡号已存在！");
                //}

                var bankCardNumbers = _bankDao.GetByCardNumber(new BankQuery() { NoEqualBcId = request.BCId, CardNumber = request.CardNumber });
                if (bankCardNumbers != null && bankCardNumbers.Any())
                {
                    throw new Exception("银行卡号已存在！");
                }

                var bankCard = new BankCard();
                if (request.BCId > 0)
                {
                    //获取银行卡
                    bankCard = _bankDao.GetById(request.BCId);
                    if (bankCard == null)
                    {
                        throw new Exception("银行卡不存在！");
                    }
                    //状态验证
                    //if (bankCard.EnableStatus != (sbyte)EnableStatus.未授权.GetHashCode())
                    //{
                    //    throw new Exception("银行卡未授权不能操作！");
                    //}
                    //订单
                    var orderRecord = _orderRecordDao.Get(bankCard.OrderNo);
                    if (orderRecord == null)
                    {
                        throw new Exception("订单号不存在！");
                    }

                    if (orderRecord.ReceiptUid == 0 || orderRecord.ReceiptUid == 0)
                    {
                        if (string.IsNullOrEmpty(request.OrderNo))
                        {
                            throw new Exception("订单编号错误");
                        }

                        bankCard.OrderNo = long.Parse(request.OrderNo);
                    }
                    else
                    {
                        bankCard.OrderNo = bankCard.OrderNo;
                    }
                }
                else
                {

                    if (string.IsNullOrEmpty(request.OrderNo))
                    {
                        throw new Exception("订单编号错误");
                    }

                    bankCard.OrderNo = long.Parse(request.OrderNo);
                }
                //银行卡号
                if (string.IsNullOrEmpty(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }
                var cardNumberReg = new Regex(@"^.{12,20}$");
                if (!cardNumberReg.IsMatch(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }

                //银行副卡号
                if (!string.IsNullOrEmpty(request.SecCardNumber))
                {
                    var secCardNumberReg = new Regex(@"^.{12,20}$");
                    if (!secCardNumberReg.IsMatch(request.SecCardNumber))
                    {
                        throw new Exception("银行副卡号必须介于 12 和 20 之间");
                    }
                }

                //银行卡用户名
                if (string.IsNullOrEmpty(request.CardName))
                {
                    throw new Exception("银行卡用户名不能为空");
                }
                if (request.CardName.Length < 2 || request.CardName.Length > 40)
                {
                    throw new Exception("银行卡用户名长度必须介于 2 和 40 之间");
                }
                //var cardNameReg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                //if (!cardNameReg.IsMatch(request.CardName))
                //{
                //    throw new Exception("银行卡用户名由中文、英文、数字包括下划线");
                //}

                //登陆名称
                if (string.IsNullOrEmpty(request.LoginName))
                {
                    throw new Exception("银行卡用户名不能为空");
                }

                if (request.LoginName.Length < 2 || request.LoginName.Length > 40)
                {
                    throw new Exception("登陆名称长度必须介于 2 和 40 之间");
                }

                var loginNameReg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                if (!loginNameReg.IsMatch(request.LoginName))
                {
                    throw new Exception("登陆名称由中文、英文、数字包括下划线");
                }

                //登陆密码
                if (string.IsNullOrEmpty(request.PasswordLogin))
                {
                    throw new Exception("登陆密码不能为空");
                }

                if (request.PasswordLogin.Length < 6 || request.PasswordLogin.Length > 40)
                {
                    throw new Exception("登陆密码长度必须介于 6 和 40 之间");
                }

                //查询密码
                if (!string.IsNullOrEmpty(request.PasswordQuery))
                {
                    if (request.PasswordQuery.Length < 6 && request.PasswordQuery.Length > 40)
                    {
                        throw new Exception("查询密码长度必须介于 6 和 40 之间");
                    }
                }

                //支付密码
                //支付密码
                if (string.IsNullOrEmpty(request.PasswordPay))
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间");
                }

                if (request.PasswordPay.Length < 6 || request.PasswordPay.Length > 8)
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间");
                }

                var passwordPayReg = new Regex(@"^[A-Za-z0-9]+$");
                if (!passwordPayReg.IsMatch(request.PasswordPay))
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间字母或数字组成");
                }
                //网盾密码
                if (string.IsNullOrEmpty(request.PasswordShield))
                {
                    throw new Exception("网盾密码长度必须介于 6 和 40 之间");
                }
                if (request.PasswordShield.Length < 6 || request.PasswordShield.Length > 40)
                {
                    throw new Exception("网盾密码长度必须介于 6 和 40 之间");
                }

                //网盾类型
                //网盾序号
                if (!string.IsNullOrEmpty(request.UsbSerialNumber))
                {
                    if (request.UsbSerialNumber.Length > 40)
                    {
                        throw new Exception("网盾类型长度必须介于 0 和 40 之间");
                    }
                }

                //原始密码
                if (string.IsNullOrEmpty(request.OriginalPassword))
                {
                    throw new Exception("原始密码不能为空");
                }

                if (request.OriginalPassword.Length < 6 || request.OriginalPassword.Length > 40)
                {
                    throw new Exception("原始密码长度必须介于 6 和 40 之间");
                }

                //开户地
                if (string.IsNullOrEmpty(request.AccountBank))
                {
                    throw new Exception("开户地不能为空");
                }
                if (request.AccountBank.Length < 1 || request.AccountBank.Length > 40)
                {
                    throw new Exception("开户地长度必须介于 6 和 40 之间");
                }

                //证件号码
                if (!string.IsNullOrEmpty(request.DocumentNumber))
                {
                    if (request.DocumentNumber.Length > 40)
                    {
                        throw new Exception("证件号码长度必须介于 0 和 40 之间");
                    }
                }

                //手机号码
                if (!string.IsNullOrEmpty(request.PhoneNumber))
                {
                    if (request.PhoneNumber.Length > 40)
                    {
                        throw new Exception("手机号码长度必须介于 0 和 40 之间");
                    }
                }
                //备注
                #endregion

                if (request.BCId > 0)
                {

                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.备用卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;
                    bankCard.UsingStatus = (sbyte)UsingStatus.冻结.GetHashCode();
                    //bankCard.EnableStatus = (sbyte)EnableStatus.未授权.GetHashCode();
                    //保持不变
                    bankCard.EnableStatus = bankCard.EnableStatus;
                    bankCard.LoginName = request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? bankCard.PasswordLogin : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? bankCard.PasswordQuery : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? bankCard.PasswordPay : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? bankCard.PasswordShield : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? bankCard.OriginalPassword : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.CompanyId = 0;
                    bankCard.Remark = string.IsNullOrEmpty(request.Remark) ? "" : request.Remark;
                    bankCard.AliPayCardIndex = request.AliPayCardIndex;
                    bankCard.AliPayBankMark = request.AliPayBankMark;
                    bankCard.AliPayCardName = request.AliPayCardName;
                    var status = _bankDao.Update(bankCard);
                    if (status)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑库存卡成功,权限编号：{0}", bankCard.Bcid);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "编辑卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "编辑卡失败！";
                    }
                }
                else
                {
                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.备用卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;
                    bankCard.UsingStatus = (sbyte)UsingStatus.冻结.GetHashCode();
                    bankCard.EnableStatus = (sbyte)EnableStatus.未授权.GetHashCode();
                    bankCard.LoginName = request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? "" : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? "" : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? "" : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = string.IsNullOrEmpty(request.UsbSerialNumber) ? "" : request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? "" : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.CompanyId = 0;
                    bankCard.Remark = request.Remark;
                    bankCard.AliPayCardIndex = request.AliPayCardIndex;
                    bankCard.AliPayBankMark = request.AliPayBankMark;
                    bankCard.AliPayCardName = request.AliPayCardName;

                    bankCard.CreateUid = request.CreateUid;
                    bankCard.CreateDate = DateTime.Now;

                    var bankCardId = _bankDao.Add(bankCard);
                    if (bankCardId > 0)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("新增库存卡成功,权限编号：{0}", bankCardId);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "新增卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "新增卡失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 根据编号获取公司
        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public List<CompanyResponse> GetCompany(int companyId, int level = 2)
        {
            return _bankDao.GetCompany(companyId, level);
        }
        #endregion

        #region 银行卡分页
        /// <summary>
        /// 银行卡分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<BankPagerResponse> GetPager(BankQuery query)
        {

            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }
            return _bankDao.GetPager(query);
        }
        #endregion

        #region 库存卡分页
        /// <summary>
        /// 库存卡查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<SpareBankCardResponse> GetSparePager(StockQuery query)
        {

            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }

            var pager = _bankDao.GetSparePager(query);

            return pager;
        }
        #endregion

        #region 库存卡[更新授权状态]
        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult UpdateAuthStatus(int bcId, sbyte enableStatus)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bank = _bankDao.GetById(bcId);
                if (bank == null)
                {
                    throw new Exception("库存卡记录不存在！");
                }

                if (bank.CardType != CardType.备用卡.GetHashCode())
                {
                    throw new Exception("银行卡的类型已发生改变");
                }

                if (bank.CompanyId > 0)
                {
                    throw new Exception("银行卡已绑定公司，不可收回");
                }

                if (enableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                {
                    if (bank.EnableStatus != (sbyte)EnableStatus.禁用.GetHashCode())
                    {
                        throw new Exception("银行卡的启用状态已发生改变");
                    }
                }

                if (_bankDao.UpdateEnableStatus(bcId, enableStatus))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    //_logRecord.LogRemark = string.Format("更新银行卡状态成功,银行卡编号：{0},状态值：{1}", bcId, enableStatus);
                    _logRecord.LogRemark = string.Format("更新库存卡状态成功,卡号：{0},用户名：{1},状态值：{2}", bank.CardNumber, bank.CardName, enableStatus);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态失败,银行卡编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 付款卡修改
        /// <summary>
        /// 付款卡修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult PaymentCardEdit(PaymentCardEditRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //付款区间起
                if (string.IsNullOrEmpty(request.PaymentStart))
                {
                    throw new Exception("付款区间起最大保留四位小数，整数最多保留五位");
                }
                var paymentStartReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                if (!paymentStartReg.IsMatch(request.PaymentStart))
                {
                    throw new Exception("付款区间起最大保留四位小数，整数最多保留五位");
                }
                //付款区间迄
                if (string.IsNullOrEmpty(request.PaymentEnd))
                {
                    throw new Exception("付款区间迄最大保留四位小数，整数最多保留五位");
                }
                var paymentEndReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                if (!paymentStartReg.IsMatch(request.PaymentEnd))
                {
                    throw new Exception("付款区间迄最大保留四位小数，整数最多保留五位");
                }
                //付款区间迄大于付款区间起
                var paymentStart = decimal.Parse(request.PaymentStart);
                var paymentEnd = decimal.Parse(request.PaymentEnd);
                if (paymentEnd <= paymentStart)
                {
                    throw new Exception("付款区间迄必须大于付款区间起");
                }
                //跨行转账
                if (!request.CrossBankPay.HasValue)
                {
                    throw new Exception("请选择跨行转账！");
                }
                //存款等级
                if (string.IsNullOrEmpty(request.DepositType))
                {
                    throw new Exception("请选择存款等级");
                }
                //银行卡启用状态
                if (!request.EnableStatus.HasValue)
                {
                    throw new Exception("请选择银行卡启用状态！");
                }

                //获取银行卡
                var bankCard = _bankDao.GetById(request.BcId);
                if (bankCard == null)
                {
                    throw new Exception("付款卡不存在！");
                }

                var requestData = JsonConvert.SerializeObject(bankCard);

                bankCard.PaymentStart = Convert.ToDecimal(request.PaymentStart);
                bankCard.PaymentEnd = Convert.ToDecimal(request.PaymentEnd);
                bankCard.CrossBankPay = (sbyte)request.CrossBankPay;
                bankCard.DepositType = request.DepositType;
                bankCard.EnableStatus = (sbyte)request.EnableStatus;

                if (string.IsNullOrEmpty(request.VmClientId))
                {
                    bankCard.VmClientId = null;
                }
                else {
                    bankCard.VmClientId = request.VmClientId;
                }
                bankCard.VmClientIdUpdateDate = DateTime.Now;
                if (!request.UserPermission.Contains("PaymentRecord0013")) {
                    bankCard.Remark = request.Remark;
                }
                bankCard.UsingStatusRemark = request.UsingStatusRemark;
               
                var status = _bankDao.Update(bankCard);
                if (status)
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("编辑付款卡成功,权限编号：{0}", bankCard.Bcid);
                    _logRecord.RequestData = requestData;
                    _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                    _logDao.Insert(_logRecord);

                    response.Success = true;
                    response.SuccessMessage = "编辑卡成功！";
                }
                else
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("编辑付款卡成功,权限编号：{0}", bankCard.Bcid);
                    _logDao.Insert(_logRecord);

                    response.Success = false;
                    response.SuccessMessage = "编辑卡失败！";
                }
            }
            catch (Exception ex)
            {
                //日志
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
        #endregion

        #region 作废
        /// <summary>
        /// 作废
        /// </summary>
        /// <param name="bcId"></param>
        /// <returns></returns>
        public JResult Obsolete(int bcId)
        {
            var result = new JResult()
            {
                Success = false
            };
            try
            {
                var bank = _bankDao.GetById(bcId);
                if (bank == null)
                {
                    throw new Exception("库存卡记录不存在！");
                }

                if (bank.CardType != CardType.备用卡.GetHashCode())
                {
                    throw new Exception("库存卡的类型已发生改变");
                }

                if (bank.EnableStatus != (sbyte)EnableStatus.未授权.GetHashCode())
                {
                    throw new Exception("库存卡的启用状态已发生改变");
                }

                if (_bankDao.Obsolete(bcId))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("库存卡作废成功,银行卡编号：{0}", bcId);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("库存卡作废失败,银行卡编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 作废卡还原
        /// <summary>
        /// 作废卡还原
        /// </summary>
        /// <param name="bcId">系统编号</param>
        /// <returns></returns>
        public JResult Restitute(int bcId)
        {
            return _bankDao.Restitute(bcId);
        }
        #endregion

        #region B2B库存卡分页
        /// <summary>
        /// 库存卡分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<B2BSpareBankCardResponse> GetB2BSparePager(B2BSpareBankCardQuery query)
        {
            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }

            var pager = _bankDao.GetB2BSparePager(query);
            //var data = pager.Rows;
            //if (pager.Success && pager.Rows.Count > 0 && data != null)
            //{
            //    for (int i = 0; i < data.Count; i++)
            //    {
            //        if (data[i].CardType == (sbyte)CardType.作废卡.GetHashCode())
            //        {
            //            var cardType = _cardTypeRecordDao.GetCardTypeRecordList(new BankCardTypeRecordQuery { CardNumber = data[i].CardNumber }).FirstOrDefault();
            //            if (cardType == null)
            //            {
            //                data[i].AfterCardType = (sbyte)CardType.备用卡;
            //            }
            //            else
            //            {
            //                data[i].AfterCardType = cardType.AfterCardType;
            //            }
            //        }
            //    }
            //}
            return pager;
        }
        #endregion

        #region B2B银行卡分页
        /// <summary>
        /// 银行卡分页
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public DataGrid<B2BBankCardResponse> GetB2BPager(B2BBankCardQuery query)
        {
            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }
            return _bankDao.GetB2BPager(query);
        }
        #endregion

        #region B2B银行卡[添加、修改]
        /// <summary>
        /// B2B银行卡[添加、修改]
        /// </summary>
        /// <param name="request">参数</param>
        public JResult B2BEditOrAdd(BankEditOrAddRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {

                    #region 数据验证

                    var cardTypes = new List<int>()
                    {
                        CardType.收款卡.GetHashCode(),
                        CardType.中转卡.GetHashCode(),
                        CardType.付款卡.GetHashCode()
                    };

                    //公司名称
                    if (cardTypes.Contains(request.CardType))
                    {
                        if (request.CompanyId <= 0)
                        {
                            throw new Exception($"{(CardType)request.CardType}必须选择公司！");
                        }
                    }

                    //银行卡使用状态
                    if (!request.UsingStatus.HasValue)
                    {
                        throw new Exception("请选择银行卡使用状态！");
                    }
                    //银行卡启用状态
                    if (!request.EnableStatus.HasValue)
                    {
                        throw new Exception("请选择银行卡启用状态！");
                    }
                    //查询密码
                    if (!string.IsNullOrEmpty(request.PasswordQuery))
                    {
                        if (request.PasswordQuery.Length < 6 || request.PasswordQuery.Length > 40)
                        {
                            throw new Exception("查询密码必须介于 6 和 40 之间");
                        }
                    }
                    //原始密码
                    //if (string.IsNullOrEmpty(request.OriginalPassword))
                    //{
                    //    throw new Exception("原始密码必须介于 6 和 40 之间");
                    //}
                    //var originalPasswordReg = new Regex(@"^.{6,40}$");
                    //if (!originalPasswordReg.IsMatch(request.OriginalPassword.ToString()))
                    //{
                    //    throw new Exception("原始密码必须介于 6 和 40 之间");
                    //}
                    //网盾类型
                    if (!request.UsbType.HasValue)
                    {
                        throw new Exception("请选择网盾类型！");
                    }

                    #region 中转卡
                    if (request.CardType == CardType.中转卡.GetHashCode())
                    {
                        //中转卡费率
                        if (string.IsNullOrEmpty(request.TransportRate))
                        {
                            throw new Exception("中转费率最大保留四位小数，整数最多保留五位");
                        }
                        var transportRateReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!transportRateReg.IsMatch(request.TransportRate))
                        {
                            throw new Exception("中转费率最大保留四位小数，整数最多保留五位");
                        }
                        //是否显示存款卡中
                        if (request.ShowedOnDepositCard<=0)
                        {
                            throw new Exception("请选择是否显示存款卡中.");
                        }
                        if (!new List<int> { 1, 2 }.Contains(request.ShowedOnDepositCard))
                        {
                            throw new Exception("请选择是否显示存款卡中");
                        }
                        //触发中转金额
                        if (string.IsNullOrEmpty(request.TriggeredAmount))
                        {
                            throw new Exception("触发中转金额最大保留四位小数，整数最多保留五位");
                        }
                        var triggeredAmountReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!triggeredAmountReg.IsMatch(request.TriggeredAmount))
                        {
                            throw new Exception("触发中转金额最大保留四位小数，整数最多保留五位");
                        }
                        //每次中转金额
                        if (string.IsNullOrEmpty(request.TransferredAmount))
                        {
                            throw new Exception("每次中转金额最大保留四位小数，整数最多保留五位");
                        }
                        var transferredAmountReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!transferredAmountReg.IsMatch(request.TransferredAmount))
                        {
                            throw new Exception("每次中转金额最大保留四位小数，整数最多保留五位");
                        }
                        //预留账户金额
                        if (string.IsNullOrEmpty(request.PreservedBalance))
                        {
                            throw new Exception("预留账户金额最大保留四位小数，整数最多保留五位");
                        }
                        var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!preservedBalanceReg.IsMatch(request.PreservedBalance))
                        {
                            throw new Exception("预留账户金额最大保留四位小数，整数最多保留五位");
                        }
                        //中转方式
                        if (request.TransportMethod <= 0) {
                            throw new Exception("请选择中转方式.");
                        }

                        if (!new List<int>{1,2}.Contains(request.TransportMethod))
                        {
                            throw new Exception("请选择中转方式");
                        }
                        //转入卡余额
                        if (string.IsNullOrEmpty(request.DestinationOrderSideBalance))
                        {
                            throw new Exception("转入卡余额不能为空.");
                        }
                        var destinationOrderSideBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!destinationOrderSideBalanceReg.IsMatch(request.DestinationOrderSideBalance))
                        {
                            throw new Exception("转入卡余额最大保留四位小数，整数最多保留五位");
                        }
                    }
                    #endregion

                    #region 付款卡
                    if (request.CardType == CardType.付款卡.GetHashCode())
                    {
                        //付款区间起
                        var paymentStartReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PaymentStart.ToString()))
                        {
                            throw new Exception("付款区间起最大保留四位小数，整数最多保留五位");
                        }
                        //付款区间迄
                        var paymentEndReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PaymentEnd.ToString()))
                        {
                            throw new Exception("付款区间迄最大保留四位小数，整数最多保留五位");
                        }
                        //付款区间迄大于付款区间起
                        var paymentStart = decimal.Parse(request.PaymentStart);
                        var paymentEnd = decimal.Parse(request.PaymentEnd);
                        if (paymentEnd <= paymentStart) {
                            throw new Exception("付款区间迄必须大于付款区间起");
                        }
                        //付款费率
                        var payFeeRatioReg = new Regex(@"^(([1-9]\d{0,4})|0)(?:\.[0-9]{1,4})?$");
                        if (!paymentStartReg.IsMatch(request.PayFeeRatio.ToString()))
                        {
                            throw new Exception("付款费率最大保留四位小数，整数最多保留五位");
                        }
                        var sysConfigList = _sysConfigDao.GetList(new SysConfigQuery() { ConfigCode = "PaymentInterface" });
                        if (sysConfigList == null || sysConfigList.Count <= 0)
                        {
                            throw new Exception("请设置公司的付款类型");
                        }

                        if (!request.PaymentType.HasValue)
                        {
                            throw new Exception("请设置公司的付款类型");
                        }

                        var configValueArray = sysConfigList.Select(p => p.ConfigValue).ToList();
                        if (!configValueArray.Contains(request.PaymentType.Value))
                        {
                            throw new Exception("请设置公司的付款类型");
                        }
                    }
                    #endregion

                    //跨行转账
                    if (!request.CrossBankPay.HasValue)
                    {
                        throw new Exception("请选择跨行转账！");
                    }
                    //证件号码
                    if (!string.IsNullOrEmpty(request.DocumentNumber))
                    {
                        var documentNumberReg = new Regex(@"^.{0,40}$");
                        if (!documentNumberReg.IsMatch(request.DocumentNumber))
                        {
                            throw new Exception("证件号码必须介于 0 和 40 之间");
                        }
                    }
                    //存款等级
                    if (request.CardType == CardType.付款卡.GetHashCode())
                    {
                        if (string.IsNullOrEmpty(request.DepositType))
                        {
                            throw new Exception("请选择存款等级");
                        }
                    }
                    else
                    {

                        var depositFeeRatioReg = new Regex(@"^(([1-9]\d{0,3})|0)(?:\.[0-9]{1,4})?$");
                        if (!depositFeeRatioReg.IsMatch(request.DepositFeeRatio.ToString()))
                        {
                            throw new Exception("收款费率最大保留四位小数，整数最多保留四位");
                        }
                    }
                    //备注
                    var bankCardExtraLimit = new BankCardExtraLimit();
                    //额外限制
                    //关闭时间、开启时间
                    var limit = new List<int>() { 1, 2 };
                    //if (request.LimitCloseDate.HasValue)
                    //{
                    //    bankCardExtraLimit.LimitCloseDate = request.LimitCloseDate;
                    //}
                    //if (request.LimitOpenDate.HasValue)
                    //{
                    //    bankCardExtraLimit.LimitOpenDate = request.LimitOpenDate;
                    //}
                    //每天执行
                    //if (request.LimitRepeat.HasValue)
                    //{
                    //    if (!limit.Contains(request.LimitRepeat.Value))
                    //    {
                    //        throw new Exception("每天执行参数错误");
                    //    }
                    //    bankCardExtraLimit.LimitRepeat = request.LimitRepeat.Value;
                    //}
                    //else
                    //{
                    //    throw new Exception("请选择每天执行开关！");
                    //}

                    if (request.CardType == CardType.收款卡.GetHashCode()) {
                        //限制收款金额
                        if (!string.IsNullOrEmpty(request.LimitDepositAmount))
                        {
                            var limitDepositAmountReg = new Regex(@"^(([1-9]\d{0,7})|0)(?:\.[0-9]{1,2})?$");
                            if (!limitDepositAmountReg.IsMatch(request.LimitDepositAmount))
                            {
                                throw new Exception("限制收款金额最大保留二位小数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitDepositAmount = decimal.Parse(request.LimitDepositAmount);
                        }
                        //限制收款笔数
                        if (!string.IsNullOrEmpty(request.LimitDepositCount))
                        {
                            var limitDepositCountReg = new Regex(@"^(([1-9]\d{0,7})|0)?$");
                            if (!limitDepositCountReg.IsMatch(request.LimitDepositCount))
                            {
                                throw new Exception("限制收款笔数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitDepositCount = int.Parse(request.LimitDepositCount);
                        }
                        //状态
                        if (request.LimitStatus.HasValue)
                        {
                            if (!limit.Contains(request.LimitStatus.Value))
                            {
                                throw new Exception("状态参数错误");
                            }
                            bankCardExtraLimit.LimitStatus = request.LimitStatus.Value;
                        }
                        else
                        {
                            throw new Exception("请选择状态开关！");
                        }
                    }
                    else if (request.CardType == CardType.付款卡.GetHashCode())
                    {
                        //限制付款金额
                        if (!string.IsNullOrEmpty(request.LimitPayAmount))
                        {
                            var limitPayAmountReg = new Regex(@"^(([1-9]\d{0,7})|0)(?:\.[0-9]{1,2})?$");
                            if (!limitPayAmountReg.IsMatch(request.LimitPayAmount))
                            {
                                throw new Exception("限制付款金额最大保留二位小数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitPayAmount = decimal.Parse(request.LimitPayAmount);
                        }
                        //限制付款笔数
                        if (!string.IsNullOrEmpty(request.LimitPayCount))
                        {
                            var limitPayCountReg = new Regex(@"^(([1-9]\d{0,7})|0)?$");
                            if (!limitPayCountReg.IsMatch(request.LimitPayCount))
                            {
                                throw new Exception("限制付款笔数，整数最多保留八位");
                            }
                            bankCardExtraLimit.LimitPayCount = int.Parse(request.LimitPayCount);
                        }
                        //状态
                        if (request.LimitStatus.HasValue)
                        {
                            if (!limit.Contains(request.LimitStatus.Value))
                            {
                                throw new Exception("状态参数错误");
                            }
                            bankCardExtraLimit.LimitStatus = request.LimitStatus.Value;
                        }
                        else
                        {
                            throw new Exception("请选择状态开关！");
                        }
                    }
                    //转付款
                    //if (request.LimitChangetoPay.HasValue)
                    //{
                    //    if (!limit.Contains(request.LimitChangetoPay.Value))
                    //    {
                    //        throw new Exception("转付款参数错误");
                    //    }
                    //    bankCardExtraLimit.LimitChangetoPay = request.LimitChangetoPay.Value;
                    //}
                    //else
                    //{
                    //    throw new Exception("请选择转付款开关！");
                    //}


                    //转收款
                    //if (request.LimitChangetoDeposit.HasValue)
                    //{
                    //    if (!limit.Contains(request.LimitChangetoDeposit.Value))
                    //    {
                    //        throw new Exception("转收款参数错误");
                    //    }
                    //    bankCardExtraLimit.LimitChangetoDeposit = request.LimitChangetoDeposit.Value;
                    //}
                    //else
                    //{
                    //    throw new Exception("请选择转付款开关！");
                    //}
                    

                    #endregion

                    if (request.BcId > 0)
                    {
                        var model = _bankDao.GetById(request.BcId, _context);
                        if (model == null)
                        {
                            throw new Exception("获取银行卡记录失败！");
                        }

                        var requestData = JsonConvert.SerializeObject(model);
                        //状态验证
                        if (model.EnableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                        {
                            throw new Exception("银行卡未授权不能操作！");
                        }

                        #region 银行卡类型记录
                        if (model.CardType != request.CardType)
                        {
                            var recordType = model.CardType == (sbyte)CardType.备用卡.GetHashCode() ? (sbyte)1 : (sbyte)2;
    
                            var bankCardTypeRecord = new BankCardTypeRecord()
                            {
                                CardNumber = model.CardNumber,
                                BeforeCardType = model.CardType,
                                AfterCardType = request.CardType,
                                RecordType = recordType,
                                CreateUid = request.UserId,
                                CreateDbdate = DateTime.Now
                            };
                            var bankCardTypeRecordId = _bankDao.BankCardTypeRecordAdd(bankCardTypeRecord, _context);
                            if (bankCardTypeRecordId <= 0)
                            {
                                throw new Exception("创建银行卡类型记录失败！");
                            }
                        }
                        #endregion

                        #region 银行卡
                        //公司名称
                        if (cardTypes.Contains(request.CardType))
                        {
                            model.CompanyId = request.CompanyId;
                        }
                        else
                        {
                            model.CompanyId = 0;
                        }
                        model.CardType = request.CardType;
                        model.UsingStatus = request.UsingStatus.Value;
                        model.EnableStatus = request.EnableStatus.Value;
                        model.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                        model.UsbType = request.UsbType.Value;
                        if (request.CardType == (sbyte)CardType.付款卡.GetHashCode())
                        {
                            model.PaymentStart = decimal.Parse(request.PaymentStart);
                            model.PaymentEnd = decimal.Parse(request.PaymentEnd);
                            model.PayFeeRatio = decimal.Parse(request.PayFeeRatio) > 0 ? decimal.Parse(request.PayFeeRatio) / 100 : 0; ;
                            model.CrossBankPay = request.CrossBankPay.Value;
                            model.DepositType = request.DepositType;
                            model.PaymentType = request.PaymentType.Value;
                        }
                        else if (request.CardType == (sbyte)CardType.中转卡.GetHashCode())
                        {
                            model.TransportRate = decimal.Parse(request.TransportRate) / 100;
                        }
                        else
                        {
                            model.PaymentStart = 0;
                            model.PaymentEnd = 0;
                            model.PayFeeRatio = 0;
                            model.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                            model.DepositType = "";
                            model.DepositFeeRatio = decimal.Parse(request.DepositFeeRatio) > 0 ? decimal.Parse(request.DepositFeeRatio) / 100 : 0;
                        }
                        model.AliPayCardIndex = request.AliPayCardIndex;
                        model.AliPayBankMark = request.AliPayBankMark;
                        model.AliPayCardName = request.AliPayCardName;
                        model.Remark = request.Remark;

                        if (!_bankDao.Update(model, _context))
                        {
                            throw new Exception("修改银行卡信息失败！");
                        }
                        #endregion

                        #region 中转卡
                        //var transportCard = _bankDao.GetTransportCard(model.Bcid, _context);
                        //if (transportCard != null)
                        //{
                        //    transportCard.ShowedOnDepositCard = request.ShowedOnDepositCard;
                        //    transportCard.TriggeredAmount = decimal.Parse(request.TriggeredAmount);
                        //    transportCard.TransferredAmount = decimal.Parse(request.TransferredAmount);
                        //    transportCard.PreservedBalance = decimal.Parse(request.PreservedBalance);

                        //    if (request.TransportMethod == (int)TransportTransferMethod.自动)
                        //    {
                        //        if (request.DestinationCardType != null && request.DestinationCardType.Any())
                        //        {
                        //            transportCard.DestinationCardType = String.Join(",", request.DestinationCardType);
                        //        }
                        //        else {
                        //            transportCard.DestinationCardType = null;
                        //        }
                                
                        //        transportCard.DestinationOrderSideBalance = decimal.Parse(request.DestinationOrderSideBalance);
                        //        if (request.DestinationBankCodes != null && request.DestinationBankCodes.Any())
                        //        {
                        //            transportCard.DestinationBankCode = String.Join(",", request.DestinationBankCodes);
                        //        }
                        //        else
                        //        {
                        //            transportCard.DestinationBankCode = null;
                        //        }
                        //        transportCard.DestinationBCID = null;

                        //        //删除授权信息
                        //        var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                        //        _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                        //        _context.SaveChanges();
                        //    }
                        //    else {

                        //        transportCard.DestinationCardType = null;

                        //        if (request.TransportCardRules == null) {
                        //            throw new Exception("请选择转入卡！");
                        //        }

                        //        var _transportCardRule = new List<TransportCardRule>();

                        //        if (request.TransportCardRules.Any())
                        //        {
                        //            sbyte row = 1;

                        //            request.TransportCardRules.ForEach(item => {

                        //                if (string.IsNullOrEmpty(item.DestinationBcidamountLimit))
                        //                {
                        //                    throw new Exception("转入卡限定金额不能为空.");
                        //                }

                        //                var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)?$");
                        //                if (!preservedBalanceReg.IsMatch(item.DestinationBcidamountLimit))
                        //                {
                        //                    throw new Exception("转入卡限定金额最多保留五位整数");
                        //                }

                        //                _transportCardRule.Add(new TransportCardRule() {
                        //                    TransportCardBcid = transportCard.Bcid,
                        //                    Priority = row,
                        //                    DestinationBcid = item.DestinationBcid,
                        //                    DestinationBcidamountLimit = Convert.ToInt32(item.DestinationBcidamountLimit)
                        //                });

                        //                row++;
                        //            });
                        //        }

                        //        if (_transportCardRule != null && _transportCardRule.Any())
                        //        {
                        //            //删除授权信息
                        //            var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                        //            _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                        //            _context.SaveChanges();
                        //            //批量新增
                        //            _context.TransportCardRule.AddRange(_transportCardRule);
                        //            _context.SaveChanges();
                        //        }
                        //    }
                        //    var transportCardUpdateStatus = _bankDao.TransportCardUpdate(transportCard);
                        //    if (!transportCardUpdateStatus)
                        //    {
                        //        throw new Exception("修改中转卡失败！");
                        //    }
                        //}
                        //else
                        //{
                        //    transportCard = new TransportCard();
                        //    transportCard.Bcid = request.BcId;
                        //    transportCard.ShowedOnDepositCard = request.ShowedOnDepositCard;
                        //    transportCard.TriggeredAmount = decimal.Parse(request.TriggeredAmount);
                        //    transportCard.TransferredAmount = decimal.Parse(request.TransferredAmount);
                        //    transportCard.PreservedBalance = decimal.Parse(request.PreservedBalance);
                        //    if (request.TransportMethod == (int)TransportTransferMethod.自动)
                        //    {
                        //        if (request.DestinationCardType != null && request.DestinationCardType.Any())
                        //        {
                        //            transportCard.DestinationCardType = String.Join(",", request.DestinationCardType);
                        //        }
                        //        else
                        //        {
                        //            transportCard.DestinationCardType = null;
                        //        }

                        //        transportCard.DestinationOrderSideBalance = decimal.Parse(request.DestinationOrderSideBalance);
                        //        //transportCard.DestinationBankCode = request.DestinationBankCode;
                        //        if (request.DestinationBankCodes != null && request.DestinationBankCodes.Any())
                        //        {
                        //            transportCard.DestinationBankCode = String.Join(",", request.DestinationBankCodes);
                        //        }
                        //        else
                        //        {
                        //            transportCard.DestinationBankCode = null;
                        //        }
                        //        transportCard.DestinationBCID = null;

                        //        //删除授权信息
                        //        var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                        //        _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                        //        _context.SaveChanges();
                        //    }
                        //    else {
                        //        transportCard.DestinationCardType = null;
                        //    }
                        //    var transportCardUpdateStatus = _bankDao.TransportCardAdd(transportCard);
                        //    if (transportCardUpdateStatus <= 0)
                        //    {
                        //        throw new Exception("新增中转卡失败！");
                        //    }

                        //    if (request.TransportMethod == (int)TransportTransferMethod.手动)
                        //    {
                        //        if (request.TransportCardRules == null)
                        //        {
                        //            throw new Exception("请选择转入卡！");
                        //        }

                        //        var _transportCardRule = new List<TransportCardRule>();

                        //        if (request.TransportCardRules.Any())
                        //        {
                        //            sbyte row = 1;

                        //            request.TransportCardRules.ForEach(item => {

                        //                if (string.IsNullOrEmpty(item.DestinationBcidamountLimit))
                        //                {
                        //                    throw new Exception("转入卡限定金额不能为空.");
                        //                }

                        //                var preservedBalanceReg = new Regex(@"^(([1-9]\d{0,4})|0)?$");
                        //                if (!preservedBalanceReg.IsMatch(item.DestinationBcidamountLimit))
                        //                {
                        //                    throw new Exception("转入卡限定金额最多保留五位整数");
                        //                }

                        //                _transportCardRule.Add(new TransportCardRule()
                        //                {
                        //                    TransportCardBcid = transportCard.Bcid,
                        //                    Priority = row,
                        //                    DestinationBcid = item.DestinationBcid,
                        //                    DestinationBcidamountLimit = Convert.ToInt32(item.DestinationBcidamountLimit)
                        //                });

                        //                row++;
                        //            });
                        //        }

                        //        if (_transportCardRule != null && _transportCardRule.Any())
                        //        {
                        //            //删除授权信息
                        //            var deleteTransportCardRules = _context.TransportCardRule.Where(c => c.TransportCardBcid == transportCard.Bcid);
                        //            _context.TransportCardRule.RemoveRange(deleteTransportCardRules);
                        //            _context.SaveChanges();
                        //            //批量新增
                        //            _context.TransportCardRule.AddRange(_transportCardRule);
                        //            _context.SaveChanges();
                        //        }
                        //    }
                        //}
                        #endregion

                        #region 银行卡额外限制
                        var bankCardExtraLimitModel = _bankDao.GetByCardNumber(model.CardNumber, _context);
                        if (bankCardExtraLimitModel != null)
                        {
                            //if (request.LimitCloseDate.HasValue)
                            //{
                            //    bankCardExtraLimitModel.LimitCloseDate = request.LimitCloseDate.Value;
                            //}
                            //if (request.LimitOpenDate.HasValue)
                            //{
                            //    bankCardExtraLimitModel.LimitOpenDate = request.LimitOpenDate.Value;
                            //}
                            //bankCardExtraLimitModel.LimitRepeat = request.LimitRepeat.Value;
                            if (!string.IsNullOrEmpty(request.LimitDepositAmount))
                            {
                                bankCardExtraLimitModel.LimitDepositAmount = decimal.Parse(request.LimitDepositAmount);
                            }
                            if (!string.IsNullOrEmpty(request.LimitDepositCount))
                            {
                                bankCardExtraLimitModel.LimitDepositCount = int.Parse(request.LimitDepositCount);
                            }
                            //bankCardExtraLimitModel.LimitChangetoPay = request.LimitChangetoPay.Value;
                            if (!string.IsNullOrEmpty(request.LimitPayAmount))
                            {
                                bankCardExtraLimitModel.LimitPayAmount = decimal.Parse(request.LimitPayAmount);
                            }
                            if (!string.IsNullOrEmpty(request.LimitPayCount))
                            {
                                bankCardExtraLimitModel.LimitPayCount = int.Parse(request.LimitPayCount);
                            }
                            //bankCardExtraLimitModel.LimitChangetoDeposit = request.LimitChangetoDeposit.Value;
                            bankCardExtraLimitModel.LimitStatus = request.LimitStatus.Value;
                            if (!_bankDao.BankCardExtraLimitUpdate(bankCardExtraLimitModel, _context))
                            {
                                throw new Exception("修改银行卡额外限制失败！");
                            }
                        }
                        else
                        {
                            bankCardExtraLimit.CardNumber = model.CardNumber;
                            if (string.IsNullOrEmpty(_bankDao.BankCardExtraLimitAdd(bankCardExtraLimit, _context)))
                            {
                                throw new Exception("添加银行卡额外限制失败！");
                            }
                        }
                        #endregion

                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑银行卡成功,权限编号：{0}", model.Bcid);
                        _logRecord.RequestData = requestData;
                        _logRecord.AffectData = JsonConvert.SerializeObject(model);
                        _logDao.Insert(_logRecord);

                        tran.Commit();

                        response.Success = true;
                        response.SuccessMessage = "修改成功！";
                    }
                    else
                    {
                        throw new Exception("参数错误！");
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        tran.Rollback();
                        //日志
                        response.ErrorMessage = ex.Message;
                    }
                    catch
                    {
                    }

                }
            }
            return response;
        }
        #endregion

        #region B2B库存卡[添加、修改]
        /// <summary>
        /// B2B库存卡[添加、修改]
        /// </summary>
        /// <param name="request"></param>
        public JResult B2BStockCardAddOrEdit(StockCardAddOrEditRequest request)
        {

            var result = new JResult()
            {
                Success = false
            };

            try
            {
                #region 数据验证
                //银行
                var bankInfo = _bankInfoDao.GetByBankCode(request.BankCode);
                if (bankInfo == null)
                {
                    throw new Exception("银行信息不存在！");
                }

                var bankCardNumbers = _bankDao.GetByCardNumber(new BankQuery() { NoEqualBcId = request.BCId, CardNumber = request.CardNumber });
                if (bankCardNumbers != null && bankCardNumbers.Any())
                {
                    throw new Exception("银行卡号已存在！");
                }

                var bankCard = new BankCard();
                if (request.BCId > 0)
                {
                    //获取银行卡
                    bankCard = _bankDao.GetById(request.BCId);
                    if (bankCard == null)
                    {
                        throw new Exception("银行卡不存在！");
                    }
                    //状态验证
                    if (bankCard.EnableStatus != (sbyte)EnableStatus.未授权.GetHashCode())
                    {
                        throw new Exception("银行卡未授权不能操作！");
                    }
                    //订单
                    //var orderRecord = _orderRecordDao.Get(bankCard.OrderNo);
                    //if (orderRecord == null)
                    //{
                    //    throw new Exception("订单号不存在！");
                    //}

                    //if (orderRecord.ReceiptUid == 0 || orderRecord.ReceiptUid == 0)
                    //{
                    //    if (string.IsNullOrEmpty(request.OrderNo))
                    //    {
                    //        throw new Exception("订单编号错误");
                    //    }

                    //    bankCard.OrderNo = long.Parse(request.OrderNo);
                    //}
                    //else
                    //{
                    //    bankCard.OrderNo = bankCard.OrderNo;
                    //}
                }
                else
                {

                    //if (string.IsNullOrEmpty(request.OrderNo))
                    //{
                    //    throw new Exception("订单编号错误");
                    //}

                    //bankCard.OrderNo = long.Parse(request.OrderNo);
                }
                //银行卡号
                if (string.IsNullOrEmpty(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }
                var cardNumberReg = new Regex(@"^.{12,20}$");
                if (!cardNumberReg.IsMatch(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }

                //银行副卡号
                if (!string.IsNullOrEmpty(request.SecCardNumber))
                {
                    var secCardNumberReg = new Regex(@"^.{12,20}$");
                    if (!secCardNumberReg.IsMatch(request.SecCardNumber))
                    {
                        throw new Exception("银行副卡号必须介于 12 和 20 之间");
                    }
                }

                //银行卡用户名
                if (string.IsNullOrEmpty(request.CardName))
                {
                    throw new Exception("银行卡用户名不能为空");
                }
                if (request.CardName.Length < 2 || request.CardName.Length > 40)
                {
                    throw new Exception("银行卡用户名长度必须介于 2 和 40 之间");
                }
                //var cardNameReg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                //if (!cardNameReg.IsMatch(request.CardName))
                //{
                //    throw new Exception("银行卡用户名由中文、英文、数字包括下划线");
                //}

                //登陆名称
                if (string.IsNullOrEmpty(request.LoginName))
                {
                    throw new Exception("银行卡用户名不能为空");
                }

                if (request.LoginName.Length < 2 || request.LoginName.Length > 40)
                {
                    throw new Exception("登陆名称长度必须介于 2 和 40 之间");
                }

                var loginNameReg = new Regex(@"^[\u4E00-\u9FA5A-Za-z0-9_]+$");
                if (!loginNameReg.IsMatch(request.LoginName))
                {
                    throw new Exception("登陆名称由中文、英文、数字包括下划线");
                }

                //登陆密码
                if (string.IsNullOrEmpty(request.PasswordLogin))
                {
                    throw new Exception("登陆密码不能为空");
                }

                if (request.PasswordLogin.Length < 6 || request.PasswordLogin.Length > 40)
                {
                    throw new Exception("登陆密码长度必须介于 6 和 40 之间");
                }

                //查询密码
                if (!string.IsNullOrEmpty(request.PasswordQuery))
                {
                    if (request.PasswordQuery.Length < 6 && request.PasswordQuery.Length > 40)
                    {
                        throw new Exception("查询密码长度必须介于 6 和 40 之间");
                    }
                }

                //支付密码
                if (string.IsNullOrEmpty(request.PasswordPay))
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间");
                }

                if (request.PasswordPay.Length < 6 || request.PasswordPay.Length > 8)
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间");
                }

                var passwordPayReg = new Regex(@"^[A-Za-z0-9]+$");
                if (!passwordPayReg.IsMatch(request.PasswordPay))
                {
                    throw new Exception("支付密码长度必须介于 6 和 8 之间字母或数字组成");
                }
                //网盾密码
                if (string.IsNullOrEmpty(request.PasswordShield))
                {
                    throw new Exception("网盾密码长度必须介于 6 和 40 之间");
                }
                if (request.PasswordShield.Length < 6 || request.PasswordShield.Length > 40)
                {
                    throw new Exception("网盾密码长度必须介于 6 和 40 之间");
                }
                //网盾类型
                //网盾序号
                if (!string.IsNullOrEmpty(request.UsbSerialNumber))
                {
                    if (request.UsbSerialNumber.Length > 40)
                    {
                        throw new Exception("网盾类型长度必须介于 0 和 40 之间");
                    }
                }

                //原始密码
                if (!string.IsNullOrEmpty(request.OriginalPassword))
                {
                    if (request.OriginalPassword.Length < 6 || request.OriginalPassword.Length > 40)
                    {
                        throw new Exception("原始密码长度必须介于 6 和 40 之间");
                    }
                }

                //开户地
                //if (string.IsNullOrEmpty(request.AccountBank))
                //{
                //    throw new Exception("开户地不能为空");
                //}
                //if (request.AccountBank.Length < 1 || request.AccountBank.Length > 40)
                //{
                //    throw new Exception("开户地长度必须介于 6 和 40 之间");
                //}

                //证件号码
                if (!string.IsNullOrEmpty(request.DocumentNumber))
                {
                    if (request.DocumentNumber.Length > 40)
                    {
                        throw new Exception("证件号码长度必须介于 0 和 40 之间");
                    }
                }

                //手机号码
                if (!string.IsNullOrEmpty(request.PhoneNumber))
                {
                    if (request.PhoneNumber.Length > 40)
                    {
                        throw new Exception("手机号码长度必须介于 0 和 40 之间");
                    }
                }
                //备注
                #endregion

                if (request.BCId > 0)
                {

                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.备用卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;

                    bankCard.UsingStatus = bankCard.UsingStatus;
                    bankCard.EnableStatus = bankCard.EnableStatus;

                    bankCard.LoginName = request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? bankCard.PasswordLogin : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? bankCard.PasswordQuery : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? bankCard.PasswordPay : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? bankCard.PasswordShield : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? "" : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = string.IsNullOrEmpty(request.AccountBank) ? "" : request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.CompanyId = 0;
                    bankCard.AliPayCardIndex = request.AliPayCardIndex;
                    bankCard.AliPayBankMark = request.AliPayBankMark;
                    bankCard.AliPayCardName = request.AliPayCardName;
                    bankCard.Remark = string.IsNullOrEmpty(request.Remark) ? "" : request.Remark;

                    var status = _bankDao.Update(bankCard);
                    if (status)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑库存卡成功,权限编号：{0}", bankCard.Bcid);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "编辑卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "编辑卡失败！";
                    }
                }
                else
                {
                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.备用卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;
                    bankCard.UsingStatus = (sbyte)UsingStatus.有效.GetHashCode();
                    bankCard.EnableStatus = (sbyte)EnableStatus.未授权.GetHashCode();
                    bankCard.LoginName = request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? "" : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? "" : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? "" : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = string.IsNullOrEmpty(request.UsbSerialNumber) ? "" : request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? "" : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = string.IsNullOrEmpty(request.AccountBank) ? "" : request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.CompanyId = 0;
                    bankCard.Remark = request.Remark;
                    bankCard.CreateUid = request.CreateUid;
                    bankCard.CreateDate = DateTime.Now;

                    var bankCardId = _bankDao.Add(bankCard);
                    if (bankCardId > 0)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCardPare_Add.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("新增库存卡成功,权限编号：{0}", bankCardId);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "新增卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "新增卡失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region B2B库存卡[更新授权状态]
        /// <summary>
        /// B2B库存卡[更新授权状态]
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult B2BUpdateAuthStatus(int bcId, sbyte enableStatus)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bank = _bankDao.GetById(bcId);
                if (bank == null)
                {
                    throw new Exception("库存卡记录不存在！");
                }

                if (bank.CardType != CardType.备用卡.GetHashCode())
                {
                    throw new Exception("银行卡的类型已发生改变");
                }

                if (enableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                {
                    if (bank.EnableStatus != (sbyte)EnableStatus.禁用.GetHashCode())
                    {
                        throw new Exception("银行卡的启用状态已发生改变");
                    }
                }

                if (bank.CompanyId > 0)
                {
                    throw new Exception("银行卡已绑定公司，不可收回");
                }

                if (_bankDao.UpdateEnableStatus(bcId, enableStatus))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    //_logRecord.LogRemark = string.Format("更新银行卡状态成功,银行卡编号：{0},状态值：{1}", bcId, enableStatus);
                    _logRecord.LogRemark = string.Format("更新库存卡状态成功,卡号：{0},用户名：{1},状态值：{2}", bank.CardNumber, bank.CardName, enableStatus);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态失败,银行卡编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region B2B更改库存卡启用状态
        /// <summary>
        /// B2B更改库存卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult B2BStockCardDelete(int bcId)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bankCard = _bankDao.GetById(bcId);
                if (bankCard == null)
                {
                    throw new Exception("银行卡记录不存在！");
                }

                if (bankCard.EnableStatus != 4)
                {
                    throw new Exception("库存卡必须为未授权状态!！");
                }

                if (bankCard.CompanyId > 0)
                {
                    throw new Exception("库存卡必须未分配公司!");
                }

                if (_bankDao.DeleteByBcId(bcId))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCardPare_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("删除银行卡成功,编号：{0}", bcId);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCardPare_Delete.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("删除银行卡失败,编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region B2B银行卡[更改启用状态]
        /// <summary>
        /// B2B银行卡[更改启用状态]
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public JResult B2BUpdateEnableStatus(int bcId, sbyte enableStatus)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                var bank = _bankDao.GetById(bcId);
                if (bank == null)
                {
                    throw new Exception("银行卡记录不存在！");
                }

                if (bank.EnableStatus == (sbyte)EnableStatus.未授权.GetHashCode())
                {
                    throw new Exception("银行卡未授权不能操作！");
                }

                if (_bankDao.UpdateEnableStatus(bcId, enableStatus))
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态成功,卡号：{0},用户名：{1},状态值：{2}", bank.CardNumber, bank.CardName, enableStatus);
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "操作成功！";
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    _logRecord.LogType = LogRecordLogType.BankCard_State.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = string.Format("更新银行卡状态失败,银行卡编号:{0},{1}", bcId, ex.Message);
                    _logDao.Insert(_logRecord);
                }
                catch { }
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        #region 作废卡
        /// <summary>
        /// 作废卡
        /// </summary>
        /// <param name="request"></param>
        public PagedList<ObsoleteBankCardResponse> GetObsoleteBankCard(ObsoleteBankCardQuery query)
        {
            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }

            var pager = _bankDao.GetObsoleteBankCard(query);
            var data = pager.TData;
            if (pager.Success && pager.TData.Count > 0 && data != null)
            {
                for (int i = 0; i < data.Count; i++)
                {
                    if (data[i].CardType == (sbyte)CardType.作废卡.GetHashCode())
                    {
                        var cardType = _cardTypeRecordDao.GetCardTypeRecordList(new BankCardTypeRecordQuery { CardNumber = data[i].CardNumber }).FirstOrDefault();
                        if (cardType == null)
                        {
                            data[i].AfterCardType = (sbyte)CardType.备用卡;
                        }
                        else
                        {
                            data[i].AfterCardType = cardType.AfterCardType;
                        }
                    }
                }
            }

            return pager;
        }
        #endregion

        #region 安全卡[添加、修改]
        /// <summary>
        /// 安全卡[添加、修改]
        /// </summary>
        /// <param name="request"></param>
        public JResult SafeCardAddOrEdit(StockCardAddOrEditRequest request)
        {

            var result = new JResult()
            {
                Success = false
            };

            try
            {
                #region 数据验证
                //银行
                var bankInfo = _bankInfoDao.GetByBankCode(request.BankCode);
                if (bankInfo == null)
                {
                    throw new Exception("银行信息不存在！");
                }

                var bankCardNumbers = _bankDao.GetByCardNumber(new BankQuery() { NoEqualBcId = request.BCId, CardNumber = request.CardNumber });
                if (bankCardNumbers != null && bankCardNumbers.Any())
                {
                    throw new Exception("银行卡号已存在！");
                }

                var bankCard = new BankCard();
                if (request.BCId > 0)
                {
                    //获取银行卡
                    bankCard = _bankDao.GetById(request.BCId);
                    if (bankCard == null)
                    {
                        throw new Exception("银行卡不存在！");
                    }
                }
                //银行卡号
                if (string.IsNullOrEmpty(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }
                var cardNumberReg = new Regex(@"^.{12,20}$");
                if (!cardNumberReg.IsMatch(request.CardNumber))
                {
                    throw new Exception("银行卡号必须介于 12 和 20 之间");
                }

                //银行副卡号
                if (!string.IsNullOrEmpty(request.SecCardNumber))
                {
                    var secCardNumberReg = new Regex(@"^.{12,20}$");
                    if (!secCardNumberReg.IsMatch(request.SecCardNumber))
                    {
                        throw new Exception("银行副卡号必须介于 12 和 20 之间");
                    }
                }

                //银行卡用户名
                if (string.IsNullOrEmpty(request.CardName))
                {
                    throw new Exception("银行卡用户名不能为空");
                }
                if (request.CardName.Length < 2 || request.CardName.Length > 40)
                {
                    throw new Exception("银行卡用户名长度必须介于 2 和 40 之间");
                }
                //备注
                #endregion

                if (request.BCId > 0)
                {

                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.安全卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;

                    bankCard.UsingStatus = bankCard.UsingStatus;
                    bankCard.EnableStatus = bankCard.EnableStatus;

                    bankCard.LoginName = string.IsNullOrEmpty(request.LoginName) ? "" : request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? bankCard.PasswordLogin : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? "" : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? "" : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? "" : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = string.IsNullOrEmpty(request.AccountBank) ? "" : request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.AliPayCardIndex = request.AliPayCardIndex;
                    bankCard.AliPayBankMark = request.AliPayBankMark;
                    bankCard.AliPayCardName = request.AliPayCardName;
                    bankCard.Remark = string.IsNullOrEmpty(request.Remark) ? "" : request.Remark;

                    var status = _bankDao.Update(bankCard);
                    if (status)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCard_Update.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("编辑安全卡成功,权限编号：{0}", bankCard.Bcid);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "编辑卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "编辑卡失败！";
                    }
                }
                else
                {
                    bankCard.BankCode = request.BankCode;
                    bankCard.BankName = bankInfo.BankName;
                    bankCard.CardType = (sbyte)CardType.安全卡.GetHashCode();
                    bankCard.CardNumber = Regex.Replace(request.CardNumber, @"\s", "");
                    bankCard.SecCardNumber = string.IsNullOrEmpty(request.SecCardNumber) ? "" : Regex.Replace(request.SecCardNumber, @"\s", "");
                    bankCard.CardName = request.CardName;
                    bankCard.UsingStatus = (sbyte)UsingStatus.有效.GetHashCode();
                    bankCard.EnableStatus = (sbyte)EnableStatus.有效.GetHashCode();
                    bankCard.LoginName = string.IsNullOrEmpty(request.LoginName) ? "" : request.LoginName;
                    bankCard.PasswordLogin = string.IsNullOrEmpty(request.PasswordLogin) ? "" : EncryptHelper.enCryptDES(request.PasswordLogin);
                    bankCard.PasswordQuery = string.IsNullOrEmpty(request.PasswordQuery) ? "" : EncryptHelper.enCryptDES(request.PasswordQuery);
                    bankCard.PasswordPay = string.IsNullOrEmpty(request.PasswordPay) ? "" : EncryptHelper.enCryptDES(request.PasswordPay);
                    bankCard.PasswordShield = string.IsNullOrEmpty(request.PasswordShield) ? "" : EncryptHelper.enCryptDES(request.PasswordShield);
                    bankCard.UsbType = request.UsbType;
                    bankCard.UsbSerialNumber = string.IsNullOrEmpty(request.UsbSerialNumber) ? "" : request.UsbSerialNumber;
                    bankCard.OriginalPassword = string.IsNullOrEmpty(request.OriginalPassword) ? "" : EncryptHelper.enCryptDES(request.OriginalPassword);
                    bankCard.AccountBank = string.IsNullOrEmpty(request.AccountBank) ? "" : request.AccountBank;
                    bankCard.DocumentNumber = string.IsNullOrEmpty(request.DocumentNumber) ? "" : request.DocumentNumber;
                    bankCard.PhoneNumber = string.IsNullOrEmpty(request.PhoneNumber) ? "" : request.PhoneNumber;
                    bankCard.BankPhoto = string.IsNullOrEmpty(request.BankPhoto) ? "" : request.BankPhoto;
                    bankCard.CompanyId = request.CompanyId;
                    bankCard.PaymentStart = 0;
                    bankCard.PaymentEnd = 0;
                    bankCard.PayFeeRatio = 0;
                    bankCard.DepositFeeRatio = 0;
                    bankCard.CrossBankPay = (sbyte)CrossBankPay.全部.GetHashCode();
                    bankCard.DepositType = "";
                    bankCard.Remark = request.Remark;
                    bankCard.CreateUid = request.CreateUid;
                    bankCard.CreateDate = DateTime.Now;

                    var bankCardId = _bankDao.Add(bankCard);
                    if (bankCardId > 0)
                    {
                        //日志
                        _logRecord.LogType = LogRecordLogType.BankCardPare_Add.GetHashCode();
                        _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                        _logRecord.CreateDate = DateTime.Now;
                        _logRecord.LogRemark = string.Format("新增安全卡成功,权限编号：{0}", bankCardId);
                        _logRecord.RequestData = JsonConvert.SerializeObject(request);
                        _logRecord.AffectData = JsonConvert.SerializeObject(bankCard);
                        _logDao.Insert(_logRecord);

                        result.Success = true;
                        result.SuccessMessage = "新增卡成功！";
                    }
                    else
                    {
                        result.Success = false;
                        result.SuccessMessage = "新增卡失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }
        #endregion

        /// <summary>
        /// 更新AdjustBalanceRID
        /// </summary>
        /// <returns></returns>
        public JResult UpdateAdjustBalanceRID(long rid)
        {
            var result = new JResult() {
                Success = false
            };
            var adjustBalance = _adjustBalanceDao.Get(rid);
            if (adjustBalance == null) {
                result.ErrorMessage = "余额变化记录不存在!";
                return result;
            }

            if (!adjustBalance.CardBcid.HasValue) {
                result.ErrorMessage = "余额变化表参数BankCardId为空!";
                return result;
            }
            return _bankDao.UpdateAdjustBalanceRID(adjustBalance.CardBcid.Value);
        }

        /// <summary>
        /// 获取有效银行卡
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public PagedList<ValidCardResponse> GetValidCard(ValidCardQuery query)
        {
            var companyIds = _bankDao.GetCompany(query.CompanyId.Value).Select(p => p.CompanyID).ToList();
            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            else
            {
                query.CompanyIds = new List<int>() { -1 };
            }
            return _bankDao.GetValidCard(query);
        }
    }
}
